package com.gitee.baqkft.time.http;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.SocketChannel;
import java.nio.channels.WritableByteChannel;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gitee.baqkft.time.TimeSyncer;

/**
 * Http时间同步方式
 * @author chenmingcai
 * @date 2019年1月7日 下午1:03:23 
 *
 */

public class HttpTimeSyncer implements TimeSyncer
{
	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public long sycToServer(String server)
	{
		InetSocketAddress addr = new InetSocketAddress(server, 80);
		SocketChannel channel = null;
		try
		{
			channel = SocketChannel.open(addr);
		}
		catch(IOException ex)
		{
			logger.error("服务器连接失败", ex);
			return 0;
		}
		
		StringBuffer builder = new StringBuffer();
		builder.append("GET / HTTP/1.1").append("\r\n");
		builder.append("Host: ").append(server).append("\r\n");
		builder.append("User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6)").append("\r\n");
		builder.append("\r\n");
		
		ByteBuffer buffer = ByteBuffer.wrap(builder.toString().getBytes());
		long t1 = System.currentTimeMillis();
		long t2= 0, t3 = 0;
		try
		{
			channel.write(buffer);
		}
		catch(IOException ex)
		{
			logger.error("发送数据失败", ex);
		}
		
		String text = null;
		try
		{
			buffer = ByteBuffer.allocate(4096);
			channel.read(buffer);
			t3 = System.currentTimeMillis();
			buffer.flip();
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			WritableByteChannel wbc = Channels.newChannel(bos);
			wbc.write(buffer);
			text = new String(bos.toByteArray());
			
			logger.debug("\n" + text);
		}
		catch(IOException ex)
		{
			logger.error("接收数据失败", ex);
		}
		finally
		{
			try
			{
				channel.close();
			}
			catch(IOException ex)
			{
				
			}
		}
		
		BufferedReader reader = new BufferedReader(new StringReader(text));
		String line;
		try
		{
			while((line = reader.readLine()) != null)
			{
				if(line.startsWith("Date"))
				{
					text = line.substring(5).trim();
					logger.debug("服务器时间:{}", text);
					
					
					SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'");
					format.setTimeZone(TimeZone.getTimeZone("GMT"));
					Date date = format.parse(text);
					
					format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					logger.debug(format.format(date));
					
					t2 = date.getTime();
					break;
				}
			}
		}
		catch(IOException | ParseException ex)
		{
			logger.error("数据解析出错", ex);
		}
		
		
		return t2 - (t1 + t3) / 2;
	}

}
